package com.user.aop.advice;

import cn.hutool.json.JSONObject;
import com.user.domain.LoginLog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.jetbrains.annotations.NotNull;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @author 1060785272@qq.com
 * @version 1.0
 * @Date 2022-4-10 下午 9:56
 */
@Aspect
@Component
@Order(1)
@Slf4j
public class PermissionFirstAdvice {
    // 定义一个切面，括号内写入第一步中自定义注解的路径
    @Pointcut("@annotation(com.user.aop.aspect.LoginLog)")
    private void loginLog() {
    }

    @AfterReturning(pointcut = "loginLog()", returning = "result")
    public void afterReturningAdvice(@NotNull JoinPoint joinPoint, Object result) {
        System.out.println("---------AfterReturning触发了----------");
        log.info("返回参数为：{}", result);

        // 也可以用来记录一些信息，比如获取请求的 URL 和 IP
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = null;
        if (attributes != null) {
            request = attributes.getRequest();
        }
        // 获取请求 IP
        String ip = null;
        String userAgent = null;
        if (request != null) {
            ip = request.getRemoteAddr();
            userAgent = request.getHeader("user-agent");
        }
        //{msg=账号不存在, code=500}
        LoginLog loginLog = new LoginLog();
        loginLog.setIp(ip);
        loginLog.setLog(userAgent);
        Object[] args = joinPoint.getArgs();
        JSONObject object = new JSONObject(result);
        String code = object.getStr("code");
        if (code.equals("500")) {
            loginLog.setState(0);
        }
        System.out.println(Arrays.toString(args));
    }

}

